import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:realmega_ota/realmega/ota_manager.dart';
import 'package:realmega_ota/realmega/ota_manager_ex.dart';
import 'package:realmega_ota/realmega/update_widget.dart';
import 'package:realmega_ota/util/ble_manager.dart';
import 'package:realmega_ota/realmega/ble_widget.dart';
import 'package:realmega_ota/realmega/setting_and_filter_manager.dart';
import 'package:realmega_ota/realmega/setting_and_filter_widget.dart';

import 'constants.dart';
import 'util/log_util.dart';

class HomeWidget extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _HomeState();
  }

}

class _HomeState extends State<HomeWidget> with AutomaticKeepAliveClientMixin{


  final double MARGIN_LENGTH = COMMON_MARGIN_LENGTH;
  // String _addrFilter = '';
  // String _nameFilter = '';

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return StreamBuilder<bool>(
        stream: OtaManagerEx.instance.inUpdate,
        initialData: false,
        builder: (c, snapshot) => Visibility(
          visible: snapshot.data!,
          replacement: RefreshIndicator(
              onRefresh: () {
                return BleManager.startScan();
              },
              child: SingleChildScrollView(
                physics: const AlwaysScrollableScrollPhysics(),
                child: Column(
                  children: <Widget>[
                    SettingAndFilterWidget(
                        onSettingInfoCallback: (String filePath, String mac, bool isVersionCheck, String creditCode){
                          Log.d('filePath:$filePath, mac:$mac, isVersionCheck:$isVersionCheck, creditCode:$creditCode');
                        },
                        onFilterInfoCallback: (String addrFilter, String nameFilter){
                          Log.d('addrFilter:$addrFilter, nameFilter:$nameFilter');
                          // _addrFilter = addrFilter;
                          // _nameFilter = nameFilter;
                          // BleManager.startScan();
                        }),
                    // StreamBuilder<List<BluetoothDevice>>(
                    //   stream: Stream.periodic(const Duration(seconds: 20))
                    //       .asyncMap((_) => BleManager.getConnectedDevices()),
                    //   initialData: [],
                    //   builder: (c, snapshot) => Column(
                    //     children: snapshot.data!.where((element) => _filterNameAndAddr(element)).map((d) => BleWidget(
                    //         device: d,
                    //         onTap: () {
                    //
                    //         }),
                    //     ).toList(),
                    //   ),
                    // ),
                    StreamBuilder<List<ScanResult>>(
                      stream: BleManager.getScanResults(),
                      initialData: [],
                      builder: (c, snapshot) => Column(
                        children: snapshot.data!.where((element) => element.advertisementData.connectable)
                            .where((element) => _filterNameAndAddr(element.device))
                            .map((r) => BleWidget(
                            result: r,
                            onTap: () {

                            }),
                        ).toList(),
                      ),
                    ),
                  ],
                ),
              )),
          child: const UpdateWidget(),
        )
    );
  }

  bool _filterNameAndAddr(BluetoothDevice device){

    String name = device.name;
    String addr = device.id.toString();

    bool nameReg = RegExp(SettingAndFilterManager.instance.advNameFilter).hasMatch(name);
    bool addrReg = RegExp(SettingAndFilterManager.instance.addressFilter).hasMatch(addr);

    // Log.d('devicename:$name, nameReg:${SettingAndFilterManager.instance.advNameFilter}, deviceAddr:$addr, addrReg:${SettingAndFilterManager.instance.addressFilter}');

    return nameReg && addrReg;
  }

  @override
  bool get wantKeepAlive => true;
}
